package com.liyuxiang.graph.node;

import com.alibaba.cloud.ai.graph.NodeOutput;
import com.alibaba.cloud.ai.graph.OverAllState;
import com.alibaba.cloud.ai.graph.action.NodeAction;
import com.alibaba.cloud.ai.graph.async.AsyncGenerator;
import com.alibaba.cloud.ai.graph.streaming.StreamingChatGenerator;
import com.liyuxiang.graph.service.DiagnosisContextService;
import com.liyuxiang.graph.context.DiagnosisContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.model.ChatResponse;
import org.springframework.ai.chat.prompt.PromptTemplate;
import reactor.core.publisher.Flux;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

public class StreamIntentRecognitionNode implements NodeAction {
    
    private static final Logger logger = LoggerFactory.getLogger(StreamIntentRecognitionNode.class);
    
    private final ChatClient chatClient;
    private final DiagnosisContextService contextService;
    
    private static final String INTENT_RECOGNITION_TEMPLATE = """
            你是专业的医疗意图识别助手，需要分析用户输入并判断是否包含明确的医疗意图。
            
            用户输入: {query}
            对话历史: {conversationHistory}
            
            请分析用户输入的意图类型，区分以下几种情况：
            1. 有意图 - 明确的症状描述、健康问题、身体不适等医疗相关咨询
            2. 无意图 - 打招呼、闲聊、测试、询问功能等非医疗内容
            
            分析要点：
            - 关注医疗相关关键词和症状描述
            - 考虑对话上下文和用户真实意图
            - 区分真实医疗咨询和功能测试
            
            请返回JSON格式分析结果：
            {{
              "intent": "有意图或无意图",
              "confidence": 0.8,
              "reason": "判断理由",
              "keywords": ["关键词1", "关键词2"],
              "medicalTerms": ["医疗术语1", "医疗术语2"],
              "riskLevel": "low",
              "nextAction": "建议的下一步操作"
            }}
            """;
    
    public StreamIntentRecognitionNode(ChatClient.Builder chatClientBuilder, DiagnosisContextService contextService) {
        this.chatClient = chatClientBuilder.build();
        this.contextService = contextService;
    }
    
    @Override
    public Map<String, Object> apply(OverAllState state) throws Exception {
        String query = state.value("query", "");
        String userId = state.value("userId", "unknown");
        String threadId = state.value("threadId", "unknown");
        
        // 获取实时对话历史
        final List<String> realTimeHistory;
        Optional<DiagnosisContext> contextOpt = contextService.getContext(threadId);
        if (contextOpt.isPresent()) {
            realTimeHistory = contextOpt.get().getConversationHistory();
        } else {
            realTimeHistory = List.of();
        }
        
        logger.info("开始流式意图识别 - 用户ID: {}, 输入: {}, 历史轮次: {}", 
                userId, query, realTimeHistory.size());
        
        // 构建对话历史字符串
        String conversationContext = buildConversationContext(realTimeHistory);
        
        // 创建流式AI调用 - 正确使用PromptTemplate
        Map<String, Object> templateParams = new HashMap<>();
        templateParams.put("query", query);
        templateParams.put("conversationHistory", conversationContext);
        
        PromptTemplate promptTemplate = new PromptTemplate(INTENT_RECOGNITION_TEMPLATE);
        String renderedPrompt = promptTemplate.render(templateParams);
        
        Flux<ChatResponse> chatResponseFlux = this.chatClient.prompt()
                .user(renderedPrompt)
                .stream()
                .chatResponse();
        
        // 创建流式生成器
        AsyncGenerator<? extends NodeOutput> generator = StreamingChatGenerator.builder()
                                                                               .startingNode("intentRecognitionStream")
                                                                               .startingState(state)
                                                                               .mapResult(response -> {
                    String text = response.getResult().getOutput().getText();
                    logger.info("意图识别流式响应: {}", text);
                    
                    // 解析AI响应
                    final String finalQuery = query;
                    Map<String, Object> intentResult = parseIntentResponse(text, finalQuery, realTimeHistory);
                    
                    return intentResult;
                })
                                                                               .build(chatResponseFlux);
        
        // 返回流式生成器
        Map<String, Object> result = new HashMap<>();
        result.put("intentAnalysis", generator);
        result.put("conversationHistory", realTimeHistory);
        
        logger.info("流式意图识别节点配置完成 - 用户ID: {}", userId);
        
        return result;
    }
    
    private String buildConversationContext(List<String> conversationHistory) {
        if (conversationHistory == null || conversationHistory.isEmpty()) {
            return "无对话历史";
        }
        
        // 取最后3轮对话作为上下文
        int start = Math.max(0, conversationHistory.size() - 6);
        List<String> recentHistory = conversationHistory.subList(start, conversationHistory.size());
        
        StringBuilder context = new StringBuilder();
        for (String message : recentHistory) {
            context.append(message).append("\n");
        }
        
        return context.toString().trim();
    }
    
    private Map<String, Object> parseIntentResponse(String response, String originalQuery, List<String> history) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 尝试解析JSON响应
            if (response.contains("{") && response.contains("}")) {
                int startIndex = response.indexOf('{');
                int endIndex = response.lastIndexOf('}') + 1;
                String jsonStr = response.substring(startIndex, endIndex);
                
                // 这里简化处理，实际项目中应该使用JsonParser
                result.put("intentType", extractJsonValue(jsonStr, "intent", "有意图"));
                result.put("confidence", Double.parseDouble(extractJsonValue(jsonStr, "confidence", "0.8")));
                result.put("reason", extractJsonValue(jsonStr, "reason", "AI分析结果"));
                result.put("riskLevel", extractJsonValue(jsonStr, "riskLevel", "medium"));
                result.put("fullAiAnalysis", true);
            } else {
                // 文本分析备用方案
                result.put("intentType", analyzeIntentFromText(response, originalQuery));
                result.put("confidence", 0.7);
                result.put("reason", "基于文本内容分析");
                result.put("riskLevel", "medium");
                result.put("fullAiAnalysis", false);
            }
            
            // 更新对话历史
            List<String> updatedHistory = new java.util.ArrayList<>(history);
            String currentUserInput = "用户: " + originalQuery;
            if (!updatedHistory.contains(currentUserInput)) {
                updatedHistory.add(currentUserInput);
            }
            result.put("conversationHistory", updatedHistory);
            
        } catch (Exception e) {
            logger.error("解析意图识别响应失败: {}", e.getMessage());
            
            // 提供默认值
            result.put("intentType", "有意图");
            result.put("confidence", 0.5);
            result.put("reason", "解析失败，使用默认判断");
            result.put("riskLevel", "medium");
            result.put("fullAiAnalysis", false);
            result.put("error", e.getMessage());
        }
        
        return result;
    }
    
    private String extractJsonValue(String json, String key, String defaultValue) {
        try {
            String pattern = "\"" + key + "\"\\s*:\\s*\"([^\"]+)\"";
            java.util.regex.Pattern p = java.util.regex.Pattern.compile(pattern);
            java.util.regex.Matcher m = p.matcher(json);
            if (m.find()) {
                return m.group(1);
            }
        } catch (Exception e) {
            logger.warn("提取JSON值失败 - key: {}, 错误: {}", key, e.getMessage());
        }
        return defaultValue;
    }
    
    private String analyzeIntentFromText(String response, String originalQuery) {
        String lowerResponse = response.toLowerCase();
        String lowerQuery = originalQuery.toLowerCase();
        
        // 医疗相关关键词
        String[] medicalKeywords = {"症状", "疼痛", "不舒服", "病", "治疗", "检查", "医院", "科室"};
        String[] casualKeywords = {"你好", "测试", "功能", "介绍", "怎么用"};
        
        // 检查原始查询
        for (String keyword : medicalKeywords) {
            if (lowerQuery.contains(keyword)) {
                return "有意图";
            }
        }
        
        for (String keyword : casualKeywords) {
            if (lowerQuery.contains(keyword)) {
                return "无意图";
            }
        }
        
        // 检查AI响应内容
        if (lowerResponse.contains("医疗") || lowerResponse.contains("症状") || lowerResponse.contains("有意图")) {
            return "有意图";
        }
        
        return "无意图";
    }
}